/* 
 * File:   Stack.cpp
 * Author: thomas
 * 
 * Created on 08. Oktober 2010, 00:31
 */

template <class Val>
Stack<Val>::Stack() {
    asize = 0;

    int initSize = 2;
    array = (Val*)malloc(initSize * sizeof(Val));
    memsize = initSize;
}

template <class Val>
Stack<Val>::Stack(const Stack& orig) {
    array = (Val*)malloc(sizeof(Val) * orig.size());
    memcpy(array, orig.getArray(), sizeof(Val) * orig.size());

    asize = orig.size();
    memsize = asize;
}

template <class Val>
Stack<Val>::~Stack() {
    free(array);
}

template <class Val>
const Val* const Stack<Val>::getArray() const {
    return array;
}

template <class Val>
Val Stack<Val>::operator [] (int i) const {
    return array[i];
}

template <class Val>
int Stack<Val>::size() const {
    return asize;
}

template <class Val>
void Stack<Val>::reset() {
    asize = 0;
}

template <class Val>
int Stack<Val>::push(const Val &item) {
    asize++;

    if(asize > memsize) {
        int new_memsize = (int)(memsize + memsize/2);

        array = (Val*)realloc(array, sizeof(Val) * new_memsize);
        memsize = new_memsize;
    }

    array[asize-1] = item;

    return asize-1;
}

template <class Val>
Val* Stack<Val>::pop() {
    Val* last = new Val(array[asize-1]);

    // TODO fix this
    /*int newsize = (int)(memsize - memsize/2);
    if(asize-1 <= newsize) {
        Val* tmparray = (Val*)malloc(sizeof(Val) * newsize);
        memcpy(tmparray, array, sizeof(Val) * newsize);
        free(array);

        array = tmparray;

        memsize = newsize;
    }*/

    asize--;

    return last;
}



